package com.magi.core;

import com.magi.exception.TypeMappingNotFoundException;

import java.io.*;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

public class AppUtils {

    public static boolean isLetter(char ch) {
        int chi = ch - 32;
        return chi >= 65 && chi <= 90;
    }

    public static String underline2camel(String underline) {
        StringBuilder builder = new StringBuilder(underline);
        int index = 1;
        for (;;) {
            index = builder.indexOf("_", index);
            if (index == -1 || index == builder.length() - 1) { break; }
            builder.replace(index, index + 2, builder.substring(index + 1, index + 2).toUpperCase());
        }
        return builder.toString();
    }

    public static String upperCamel2lowerCamel(String upperCamel) {
        StringBuilder builder = new StringBuilder(underline2camel(upperCamel));
        return builder.replace(0, 1, builder.substring(0, 1).toLowerCase()).toString();
    }

    public static String lowerCamel2upperCamel(String lower) {
        StringBuilder builder = new StringBuilder(underline2camel(lower));
        return builder.replace(0, 1, builder.substring(0, 1).toUpperCase()).toString();
    }

    public static String getMapperName(TableMetaData metaData) {
        return lowerCamel2upperCamel(getPojoName(metaData) + "Mapper");
    }

    public static String getPojoName(TableMetaData metaData) {
        return lowerCamel2upperCamel(underline2camel(metaData.getTableName()));
    }

    public static String tableName2className(String tableName) {
        return lowerCamel2upperCamel(underline2camel(tableName));
    }

    public static String columnName2fieldName(String columnName) {
        return underline2camel(columnName);
    }

    public static ClassMetaData tableMetaData2classMetaData(TableMetaData metaData, IDatabaseTypeMapping typeMapping) throws TypeMappingNotFoundException {
        Iterator<TableMetaData.Column> cols = metaData.getColumnIterator();
        List<ClassMetaData.Field> fieldList = new ArrayList<>();
        while(cols.hasNext()) {
            TableMetaData.Column col = cols.next();
            fieldList.add(new ClassMetaData.Field(
                    typeMapping.getJavaType(col.getType()),
                    AppUtils.columnName2fieldName(col.getName())
            ));
        }
        return new ClassMetaData(
                AppUtils.tableName2className(metaData.getTableName()),
                fieldList
        );
    }

    public static void writeToFile(String filename, String text) throws IOException {
        try (FileWriter writer = new FileWriter(filename)) {
            writer.write(text);
        }
    }

    public static InputStream getResourceFileStream(String filename) throws IOException {
        return ClassLoader.getSystemResourceAsStream(filename);
    }

    public static void main(String[] args) throws IOException {
    }
}
